package com.campus.controller;

import com.campus.common.CampusWall;
import com.campus.common.Result;
import com.campus.entity.Users;
import com.campus.service.PostViewService;
import com.campus.utils.TokenUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class PostViewController {
    
    @Autowired
    private PostViewService postViewService;
    
    @Autowired
    private TokenUtils tokenUtils;
    
    /**
     * 记录帖子浏览
     * @param postId
     * @param request
     * @return
     */
    @PostMapping("/post/{postId}/view")
    public Result recordPostView(@PathVariable("postId") String postId, HttpServletRequest request) {
        try {
            // 获取当前用户
            String token = request.getHeader(CampusWall.CAMPUS_TOKEN);
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Users currentUser = tokenUtils.getCurrentUser(token);
            if (currentUser == null) {
                return Result.err(Result.CODE_401, "用户未登录");
            }
            
            // 记录浏览
            return postViewService.recordPostView(postId, currentUser.getUserId());
        } catch (Exception e) {
            return Result.err(Result.CODE_500, "记录浏览失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取帖子浏览量
     * @param postId
     * @return
     */
    @GetMapping("/post/{postId}/views")
    public Result getViewCount(@PathVariable("postId") String postId) {
        return postViewService.getViewCount(postId);
    }
}